<template>
  <div>
    <vm-status v-if="hasDis === 1"
               error-text="没有入库单"
               type="error"></vm-status>

    <scroller v-else-if="hasDis === 2"
              :show-scrollbar="false">
      <text class="bg-white p-3">单号: {{dis.dis_id}}</text>
      <div class="flex-row-wp">
        <text class="dt">配送商:</text>
        <text class="dd">{{dis.service_name}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">联系人:</text>
        <text class="dd">{{dis.res_person_name}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">联系电话:</text>
        <text class="dd">{{dis.res_phone_number}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">公司地址:</text>
        <text class="dd">{{dis.service_address}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">{{+dis.ship_status === 2?'退货':'入库'}}时间:</text>
        <text class="dd">{{confirmTime}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">收货状态:</text>
        <div class="flex flex-row"
             v-if="+dis.ship_status === 0">
          <text class="btn btn-primary mr-3"
                @click="confirmShow">确认收货</text>
          <text class="btn btn-error-outline"
                @click="rejectShow">退货</text>
        </div>
        <text class="dd"
              :class="[dis.shipStatusStyle]"
              v-else>{{dis.shipStatus}}</text>
      </div>

      <div class="p-title">
        <text>物资</text>
        <div class="flex-row-e">
          <text class="small text-muted">共 {{disDetail.length}} 个, 合计 </text>
          <text class="text-error">{{dis.total_amount}}</text>
          <text class="small text-muted"> 元</text>
        </div>
      </div>

      <div class="flex-row bg-white"
           v-for="(item, index) in disDetail"
           :key="index">
        <text class="p-serial">{{index + 1}}</text>
        <div class="p-content">
          <div class="flex">
            <text class="text">{{item.product_name}}</text>
            <text class="small text-muted">规格: {{item.spec_name}}</text>
            <text class="small text-muted">日龄/使用日龄: {{item.enable_day_age || '-'}}天</text>
            <text class="small text-muted">生产商: {{item.producer_name}}</text>
          </div>
          <div class="align-right">
            <text class="text">&yen; {{item.item_total}}</text>
            <text class="small text-muted">单价: {{item.unit_price}}</text>
            <text class="small text-muted">数量: {{item.dis_num}}{{item.unit}}</text>
          </div>
        </div>
      </div>
    </scroller>

    <vm-dialog title="确定收货？"
               :show="confirmVisible"
               confirmText="收货"
               @cancelClicked="confirmCancel"
               @confirmClicked="confirmConfirm">
    </vm-dialog>

    <vm-dialog title="确定退货？"
               :show="rejectVisible"
               confirmText="退货"
               confirmColor="#e51c23"
               @cancelClicked="rejectCancel"
               @confirmClicked="rejectConfirm">
    </vm-dialog>

  </div>
</template>
<script>
import VmDialog from '../../components/vm-dialog.vue'
import VmStatus from '../../components/vm-status.vue'
import {
  enumShipStatus,
  enumShipStatusStyle
} from '../../plugins/enumChick'

export default {
  components: { VmDialog, VmStatus },
  props: {},
  data() {
    return {
      dis: {},
      disDetail: [],
      confirmTime: '',
      confirmVisible: false,
      rejectVisible: false,
      hasDis: 0
    }
  },
  computed: {

  },
  watch: {},
  created() {
    this.getParams()
  },
  methods: {
    async getParams() {
      const res = await this.$router.getParams()
      this.dis = res && res.data || {}
      if (!this.dis.dis_id) {
        const task = res && res.task || {}
        if (task.related_id) {
          this.dis.dis_id = task.related_id
          this.getDisForm().then(() => {
            this.getDetail()
          })
        } else {
          this.hasDis = 1
          this.$notice.toast({ message: '获取入库单失败' })
        }
      } else {
        this.getDetail()
      }
    },
    getDetail() {
      this.hasDis = 2
      this.getConfirmTime()
      this.getDisDetail()
    },
    getConfirmTime() {
      const shipStatus = +this.dis.ship_status // confirm_time
      if (shipStatus === 0) {
        this.confirmTime = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd')
      } else {
        this.confirmTime = this.$utils.dateFormat(this.dis.confirm_time, 'yyyy-MM-dd')
      }
    },
    async getDisDetail() {
      const res = await this.$api.getData({
        server: 'agr_chain',
        table: 'dis_form_detail',
        params: {
          'dis_id.eq': this.dis.dis_id
        },
        order: { order_num: 'asc' }
      })
      const data = res || []
      this.disDetail = data.map(item => {
        item.item_total = this.pureDot(item.item_total)
        item.unit_price = this.pureDot(item.unit_price)
        item.dis_num = this.pureDot(item.dis_num)
        return item
      })
    },
    pureDot(num) {
      return num ? num.replace(/(?:\.0*|(\.\d+?)0+)$/g, '') : ''
    },
    // 收货
    confirmShow() {
      this.confirmVisible = true
    },
    confirmCancel() {
      this.confirmVisible = false
    },
    confirmConfirm() {
      this.updateShipStatus(1)
    },
    // 退货
    rejectShow() {
      this.rejectVisible = true
    },
    rejectCancel() {
      this.rejectVisible = false
    },
    rejectConfirm() {
      this.updateShipStatus(2)
    },
    // api
    updateShipStatus(status = 1) {
      this.$notice.loading.show()
      const data = { ship_status: status }
      if (this.confirmTime) {
        data.confirm_time = this.confirmTime
      }

      // 单独更新状态后端无法更新库存，改用关联修改
      // this.$api.updateData({
      //   server: 'agr_chain',
      //   table: 'dis_form',
      //   id: this.dis.dis_id,
      //   data
      // }).then(res => {
      //   this.$notice.toast({ message: `${status === 1 ? '收货' : '退货'}成功` })
      //   this.$router.setBackParams({ type: 1 })
      //   this.getDisForm()
      // }).catch(res => {
      //   this.$notice.toast({ message: `${status === 1 ? '收货' : '退货'}失败` })
      // }).finally(() => {
      //   this.$notice.loading.hide()
      //   this.confirmVisible = false
      //   this.rejectVisible = false
      // })

      // 关联更新
      data.dis_id = this.dis.dis_id
      const slaveData = []
      for (const detail of this.disDetail) {
        slaveData.push({
          id: detail.id,
          arrival_date: this.confirmTime || this.$utils.dateFormat(new Date())
        })
      }
      this.$api.relatedUpdate({
        server: 'agr_chain',
        data: {
          masterTableInfo: JSON.stringify(data),
          masterTableName: 'dis_form',
          slaveTableInfo: JSON.stringify(slaveData),
          slaveTableName: 'dis_form_detail'
        },
        errorMsg: `${status === 1 ? '收货' : '退货'}失败`
      }).then(res => {
        this.$notice.toast({ message: `${status === 1 ? '收货' : '退货'}成功` })
        this.$router.setBackParams({ type: 1 })
        this.getDisForm()
      }).finally(() => {
        this.$notice.loading.hide()
        this.confirmVisible = false
        this.rejectVisible = false
      })
    },
    getDisForm() {
      return new Promise((resolve, reject) => {
        this.$api.getData({
          server: 'agr_chain',
          table: 'dis_form_view',
          params: {
            index: 1,
            size: 1,
            'dis_id.eq': this.dis.dis_id
          },
          errorMsg: '获取入库单失败'
        }).then(res => {
          this.dis = res && res.data && res.data.length && res.data[0] || {}
          this.dis.disDate = this.dis.dis_date ? this.dis.dis_date.substr(0, 10) : ''
          this.dis.shipStatus = enumShipStatus[this.dis.ship_status] || '其他'
          this.dis.shipStatusStyle = enumShipStatusStyle[this.dis.ship_status] || ''
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.bg-white {
  background-color: #fff;
}
.p-3 {
  padding: 30px;
}
.pt-3 {
  padding-top: 30px;
}
.pb-3 {
  padding-bottom: 30px;
}
.px-3 {
  padding-left: 30px;
  padding-right: 30px;
}
.py-1 {
  padding-top: 10px;
  padding-bottom: 10px;
}
.mt-3 {
  margin-top: 30px;
}
.mt-1 {
  margin-top: 10px;
}
.mr-3 {
  margin-right: 30px;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.justify-end {
  justify-content: flex-end;
}
.align-center {
  align-items: center;
}
.align-right {
  align-items: flex-end;
}
.small {
  font-size: 26px;
}
.mini {
  font-size: 22px;
}
.text-muted {
  color: #999;
}
.text-error {
  color: $error;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.text {
  font-size: 28px;
}
.text-right {
  text-align: right;
}
.text-info {
  color: $info;
}
.text-success {
  color: $success;
}
.text-error {
  color: $error;
}

.flex-row-e {
  flex-direction: row;
  flex: 1;
  justify-content: flex-end;
  align-items: flex-end;
}
.flex-row-wp {
  flex-direction: row;
  background-color: #fff;
  padding-left: 30px;
  padding-right: 30px;
  padding-bottom: 10px;
}
.dt {
  width: 160px;
  font-size: 26px;
  color: #666;
}
.dd {
  flex: 1;
  font-size: 26px;
}
.p-title {
  flex-direction: row;
  padding: 30px;
  background-color: #fff;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
  margin-top: 10px;
}
.p-serial {
  padding: 10px;
  width: 80px;
  color: #999;
  text-align: center;
  font-size: 26px;
}
.p-content {
  flex-direction: row;
  flex: 1;
  padding-top: 10px;
  padding-bottom: 10px;
  padding-right: 30px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}

.btn {
  padding-left: 30px;
  padding-right: 30px;
  border-width: 1px;
  height: 56px;
  line-height: 56px;
  border-radius: 6px;
}
.btn-primary {
  background-color: $primary;
  border-color: $primary;
  color: #fff;
}
.btn-error-outline {
  background-color: #fff;
  border-color: $error;
  color: $error;
}
</style>
